package com.gz.steak.modules.system.service.impl;

import com.gz.steak.common.exception.BusinessException;
import com.gz.steak.common.exception.EmBusinessError;
import com.gz.steak.modules.system.mapper.SysDeptMapper;
import com.gz.steak.modules.system.mapper.SysUserRoleMapper;
import com.gz.steak.modules.system.pojo.dataobject.SysRole;
import com.gz.steak.modules.system.pojo.model.SysUserModel;
import com.gz.steak.modules.system.pojo.vo.SysUserEditVo;
import com.gz.steak.utils.convert.ConvertUtil;
import com.gz.steak.utils.security.SpringSecurityUtil;
import com.gz.steak.modules.system.mapper.SysUserMapper;
import com.gz.steak.modules.system.pojo.dataobject.SysUser;
import com.gz.steak.modules.system.pojo.vo.SysUserVo;
import com.gz.steak.modules.system.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author 刘牌
 * @Date 2020/3/20 0020 23:16
 * @Version 1.0
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Transactional
    @Override
    public void save(SysUser sysUser, String user) {
        String username = sysUserMapper.findUserNameIsExists(sysUser.getUserName());
        if (username != null){
            throw new BusinessException(EmBusinessError.USER_ALREADY_EXISTS);
        }
        else {
            sysUser.setCreateBy(user)
                    .setCreateTime(ConvertUtil.FormatDate(new Date()))
                    .setUserStatus((byte)1)
                    .setUserBirthday(ConvertUtil.FormatDate(sysUser.getUserBirthday()))
                    .setUserPassword(SpringSecurityUtil.encode(sysUser.getUserName(),sysUser.getUserPassword()));
            int i = sysUserMapper.insertSelective(sysUser); //插入用户表
            logger.info("插入  i"+i);
            Long id = sysUserMapper.queryIdByUserName(sysUser.getUserName()); //插入成功后根据账号获取id
            Integer[] userRole = sysUser.getRolesInt();
            for (int r = 0 ; r < userRole.length ; r++){
                int s = sysUserRoleMapper.insertIfRecordNotExists(id,userRole[r]); //插入角色用户表
                logger.info("插入角色  "+s);
            }
        }

    }

    /**
     * 用户列表
     * @return
     */
    @Override
    public List<SysUserVo> list(Long nodeId) {
        List<SysUserModel> list = null;
        if (nodeId == 1){
           list = sysUserMapper.getUserList(nodeId); //查询全部用户
        }
        else {
            int count = sysDeptMapper.getCountById(nodeId); //判断是否有上级部门 为0表示是叶子节点，大于0表示还有叶子节点
            if (count == 0){
                list = sysUserMapper.getUserListOfOne(nodeId);
            }
            else {
                list = sysUserMapper.getUserListOfMore(nodeId);
            }
        }
        if (list.size() == 0){
            throw new BusinessException(EmBusinessError.RESULT_NULL);
        }
        List<SysUserModel> sysUserModelList = new ArrayList<>();
        List<SysUserVo> sysUserVoList = new ArrayList<>();
        list.forEach(user ->{
           List<SysRole> roles = sysUserRoleMapper.getRoleListByUserName(user.getId());
           List<String> roleStr = new ArrayList<>();
           List<Long> roleInt = new ArrayList<>();
           roles.forEach(r -> {
               roleStr.add(r.getRoleRemark());
               roleInt.add(r.getId());
           });
           sysUserModelList.add(user);
           SysUserVo sysUserVo = new SysUserVo();
           sysUserVo.setCreateBy(user.getCreateBy())
                   .setCreateTime(ConvertUtil.DateToString(user.getCreateTime()))
                   .setId(user.getId())
                   .setUserBirthday(user.getUserBirthday())
                   .setDeptName(user.getDeptName())
                   .setUserName(user.getUserName())
                   .setUserEmail(user.getUserEmail())
                   .setUserNickName(user.getUserNickName())
                   .setUserPhone(user.getUserPhone())
                   .setUserRole(roleStr)
                   .setRolesInt(roleInt)
                   .setUserSex(user.getUserSex())
                   .setUserStatus(user.getUserStatus())
                   .setUserDeptId(user.getUserDeptId()) ;
           sysUserVoList.add(sysUserVo);
        });
        return sysUserVoList;
    }

    @Override
    public void deleteById(Long id) {
        int i = sysUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void frozenById(Long id , int status) {
        int i = sysUserMapper.frozenById(id,status);
    }


    @Override
    @Transactional
    public void edit(SysUserEditVo sysUserEditVo) {
        SysUser sysUser = new SysUser();
        sysUser.setId(sysUserEditVo.getId())
                .setUserBirthday(sysUserEditVo.getUserBirthday())
                .setUserDeptId(sysUserEditVo.getUserDeptId())
                .setUserSex(sysUserEditVo.getUserSex())
                .setUserEmail(sysUserEditVo.getUserEmail())
                .setUserName(sysUserEditVo.getUserName())
                .setUserPhone(sysUserEditVo.getUserPhone())
                .setUserNickName(sysUserEditVo.getUserNickName());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        for (int i = 0 ; i < sysUserEditVo.getRolesInt().length ; i++){
            int a = sysUserRoleMapper.insertIfRecordNotExists(sysUserEditVo.getId(),sysUserEditVo.getRolesInt()[i]); //插入角色用户表
        }
    }
}
